package com.xiaomaoguai.fcp.pre.kepler.mock.zktool;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.KeeperException;

import java.util.concurrent.TimeUnit;

/**
 * @author WeiHui
 * @version v1.0.0
 * @date 2019/4/15 19:53
 * @since JDK 1.8
 */
@Slf4j
@Getter
@AllArgsConstructor
public enum ZkEnum {

	/**
	 * 测试
	 */
	TEST("10.139.103.1:2181"),

	;

	/**
	 * zk地址
	 */
	private final String zkServer;

	/**
	 * 用默认命名空间
	 *
	 * @return zk操作对象
	 */
	public CuratorFramework getCuratorFramework() {
		return getCuratorFramework("kepler");
	}

	/**
	 * namespace 命名空间
	 *
	 * @return zk操作对象
	 */
	public CuratorFramework getCuratorFramework(String namespace) {
		CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
				.connectString(getZkServer())
				.retryPolicy(new ExponentialBackoffRetry(
						2000,
						5,
						5000))
				.namespace(namespace);
		CuratorFramework curatorFramework = builder.build();
		curatorFramework.start();
		try {
			if (!curatorFramework.blockUntilConnected(5000 * 5, TimeUnit.MILLISECONDS)) {
				curatorFramework.close();
				throw new KeeperException.OperationTimeoutException();
			}
		} catch (Exception e) {
			log.error("zk exception", e);
		}
		return curatorFramework;
	}

}
